package com.gzhu.knowledgeAdmin.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzhu.knowledgeAdmin.common.utils.UserInfoUtils;
import com.gzhu.knowledgeAdmin.common.vo.KnowledgeAddOrUpdateVo;
import com.gzhu.knowledgeAdmin.common.vo.ZSImportVo;
import com.gzhu.knowledgeAdmin.entity.Scene;
import com.gzhu.knowledgeAdmin.entity.User;
import com.gzhu.knowledgeAdmin.entity.Zs;
import com.gzhu.knowledgeAdmin.entity.Zsfl;
import com.gzhu.knowledgeAdmin.service.SceneService;
import com.gzhu.knowledgeAdmin.service.ZsService;
import com.gzhu.knowledgeAdmin.service.ZsflService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 知识列表导入处理器
 * @author yangminggui
 * @create 2024-04-18 17:18
 */
public class ZSImportHandler extends MyImportHandler {

    ZsService zsService;
    ZsflService zsflService;

    // 导入返回信息
    StringBuilder stringBuilder = new StringBuilder();

    List<ZSImportVo> zsList;

    public ZSImportHandler(List<ZSImportVo> zsList) {
        this.zsService = SpringUtil.getBean(ZsService.class);;
        this.zsflService = SpringUtil.getBean(ZsflService.class);;
        this.zsList = zsList;
    }


    private String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入知识结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, stringBuilder.toString());
        return summaryMsg;
    }

    public Map<String, List<Integer>> buildZSflMap(List<Zsfl> zsfls) {
        Map<Integer, Zsfl> zsflMap = new HashMap(); // 用于快速查找分类
        for (Zsfl zsfl : zsfls) {
            zsflMap.put(zsfl.getId(), zsfl);
        }

        Map<String, List<Integer>> resultMap = new HashMap<>();

        for (Zsfl zsfl : zsfls) {
            // 如果为第一级分类
            if (zsfl.getSjflid() == 0) {
                findLeafCategories(zsfl, zsflMap, resultMap);
            }
        }

        return resultMap;
    }

    private void findLeafCategories(Zsfl zsfl, Map<Integer, Zsfl> zsflMap, Map<String, List<Integer>> resultMap) {
        if (zsflMap.values().stream().noneMatch(c -> c.getSjflid().equals(zsfl.getId()))) {
            // 当前分类是叶子节点
            List<Integer> list = new ArrayList<>();
            list.add(zsfl.getId());
            Zsfl parent = zsfl;
            while (parent.getSjflid() != 0 && zsflMap.containsKey(parent.getSjflid())) {
                parent = zsflMap.get(parent.getSjflid());
                if (parent.getSjflid() == 0) {
                    // 找到第一级分类
                    list.add(0, parent.getId()); // 将第一级分类ID添加到列表开头
                    break;
                }
            }
            resultMap.put(zsfl.getFlmc(), list);
        } else {
            // 当前分类不是叶子节点，递归检查子分类
            for (Zsfl c : zsflMap.values()) {
                if (c.getSjflid().equals(zsfl.getId())) {
                    findLeafCategories(c, zsflMap, resultMap);
                }
            }
        }
    }

    @Override
    public String handle() {

        List<Zsfl> list = zsflService.list();
        Map<String, List<Integer>> stringListMap = buildZSflMap(list);


        for (ZSImportVo zsImportVo : zsList) {

            String zsbt = zsImportVo.getZsbt();
            String zsfl = zsImportVo.getZsfl();
            String wtnr = zsImportVo.getWtnr();
            String hdnr = zsImportVo.getHdnr();

            StringBuilder validationMsg = new StringBuilder();

            // 知识标题是否为空
            if(!StringUtils.hasLength(zsbt)){
                validationMsg.append("知识标题为空");
            }
            // 知识分类是否为空且有效
            if(!StringUtils.hasLength(zsfl)){
                validationMsg.append("知识分类为空");
            }else if(!stringListMap.containsKey(zsfl)){
                validationMsg.append("知识分类无效");
            }
            // 问题内容是否为空
            if(!StringUtils.hasLength(wtnr)){
                validationMsg.append("问题内容为空");
            }
            // 回答内容是否为空
            if(!StringUtils.hasLength(hdnr)){
                validationMsg.append("回答内容为空");
            }


            if(validationMsg.length()==0){

                KnowledgeAddOrUpdateVo knowledgeAddOrUpdateVo = new KnowledgeAddOrUpdateVo();
                BeanUtils.copyProperties(zsImportVo,knowledgeAddOrUpdateVo);
                knowledgeAddOrUpdateVo.setZslxIds(stringListMap.get(zsfl));

                try {
                    zsService.saveZs(knowledgeAddOrUpdateVo);
                    validCount++;
                } catch (Exception e) {
                    invalidCount++;
                    stringBuilder.append("第").append(validCount + invalidCount).append("行数据保存失败；<br/>");
                    e.printStackTrace();
                }

            }else { // 验证错误

                invalidCount++;
                stringBuilder.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(validationMsg + "<br/>");
            }

        }

        return getMsg();

    }
}
